package cn.stylefeng.guns.modular.fi.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.fi.entity.FiOrderAsyc;
import cn.stylefeng.guns.modular.fi.mapper.FiOrderAsycMapper;
import cn.stylefeng.guns.modular.fi.model.params.FiOrderAsycParam;
import cn.stylefeng.guns.modular.fi.model.result.FiOrderAsycResult;
import  cn.stylefeng.guns.modular.fi.service.FiOrderAsycService;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.transport.entity.TDispatch;
import cn.stylefeng.guns.modular.transport.entity.TransportDispatch;
import cn.stylefeng.guns.modular.transport.service.TDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportDispatchService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 拣货单拉取 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2025-01-19
 */
@Service
public class FiOrderAsycServiceImpl extends ServiceImpl<FiOrderAsycMapper, FiOrderAsyc> implements FiOrderAsycService {

    @Autowired
    private OrderTransportService orderTransportService;

    @Autowired
    private TransportDispatchService transportDispatchService;

    @Autowired
    private TDispatchService tDispatchService;

    @Override
    public void add(FiOrderAsycParam param){
        FiOrderAsyc entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(FiOrderAsycParam param){
        this.removeById(getKey(param));
    }

    @Override
    public ResponseData replaceOne(FiOrderAsycParam param) {
        FiOrderAsyc fiOrderAsyc = this.getById(param.getOrderNumber());

        if(ToolUtil.isEmpty(fiOrderAsyc)){
            return ResponseData.error("未找对对应记录信息，请刷新后重试");
        }

        if(ToolUtil.isEmpty(fiOrderAsyc.getTotalvolume())){
            return ResponseData.error("选择的记录对应的体积不能替换");
        }
        //根据客户号，查找对应的体积比例
        OrderTransport orderTransport = this.orderTransportService.lambdaQuery()
                .eq(OrderTransport::getOrderNumber, fiOrderAsyc.getOrderNumber())
                .ne(OrderTransport::getTstate, "作废")
                .one();

        if(ToolUtil.isEmpty(orderTransport)){
            return ResponseData.error("未找对对应的货运信息，不能操作");
        }
        String tooVolumeStr = orderTransport.getTooVolume();
        BigDecimal rate = BigDecimal.ZERO;
        if(ToolUtil.isNotEmpty(tooVolumeStr)){
            rate = new BigDecimal(fiOrderAsyc.getTotalvolume()).divide(new BigDecimal(tooVolumeStr),6, BigDecimal.ROUND_HALF_UP) ;
        }

        if(rate.compareTo(BigDecimal.ZERO) == 0){
            return ResponseData.error("选择记录有问题，无法替换");
        }

        // 替换运单体积
        orderTransportService.lambdaUpdate()
                .eq(OrderTransport::getTransportNumber,fiOrderAsyc.getTransportNumber())
                .set(OrderTransport::getTotalVolume,fiOrderAsyc.getTotalvolume())
                .set(OrderTransport::getTooVolume,new BigDecimal(orderTransport.getTooVolume()).multiply(rate))
                .update();
        // 替换货运明细体积
        transportDispatchService.lambdaUpdate()
                .eq(TransportDispatch::getTransportNumber,fiOrderAsyc.getTransportNumber())
                .setSql("tooDeployVolume = tooDeployVolume * " + rate)
                .update();
        // 替换货运单体积
        List<TransportDispatch> list = transportDispatchService.lambdaQuery()
                .eq(TransportDispatch::getTransportNumber, fiOrderAsyc.getTransportNumber())
                .list();
        Set<String> disNumberList = new HashSet<>();
        for(TransportDispatch obj : list){
            disNumberList.add(obj.getDispatchNumber());
        }
        tDispatchService.lambdaUpdate()
                .in(TDispatch::getDispatchNumber,disNumberList)
                .setSql("toovolume = toovolume * " + rate )
                .update();
        return ResponseData.success();
    }

    /**
     * 修改【order_transport】表
     * @param ids
     * @return
     */
    private String getUpdateOrderTransportSql(String ids){
        StringBuffer sql = new StringBuffer();
        sql.append("update order_transport t1 ");
        sql.append("inner join transport_dispatch_vol_match t2 ");
        sql.append("on t1.customer_order = t2.customer_order ");
        sql.append("set t1.totalvolume = t2.cust_vol ");
        sql.append(",t1.toovolume = ROUND(t1.toovolume/t1.totalvolume * t2.cust_vol,4) ");
        sql.append("where  t1.customer_order = t2.customer_order ");
        sql.append("and t1.customer_order in ('");
        sql.append(ids.replaceAll(",","','"));
        sql.append("') ");
        System.out.println(sql.toString());
        return sql.toString();
    }

    /**
     * 修改【transport_dispatch】表
     * @param ids
     * @return
     */
    private String getUpdateTransportDispatchSql(String ids){
        StringBuffer sql = new StringBuffer();
        sql.append("update transport_dispatch t1 ");
        sql.append("inner join transport_dispatch_vol_match t2 ");
        sql.append("on t1.customer_order = t2.customer_order ");
        sql.append("set t1.tooDeployVolume = ROUND(t1.tooDeployVolume/t2.sys_toovolume *t2.cust_vol,4) ");
        sql.append("where  t1.customer_order = t2.customer_order ");
        sql.append("and t1.customer_order in ('");
        sql.append(ids.replaceAll(",","','"));
        sql.append("') ");
        System.out.println(sql.toString());
        return sql.toString();
    }

    /**
     * 修改【t_dispatch】表
     * @param ids
     * @return
     */
    private String getUpdateTDispatchSql(String ids){
        StringBuffer sql = new StringBuffer();
        sql.append("update t_dispatch t1 ");
        sql.append("inner join ( ");
        sql.append("select tt1.dispatch_number, ROUND(sum(tt1.tooDeployVolume),4) as tooDeployVolume ");
        sql.append("from transport_dispatch tt1 ");
        sql.append("where tt1.dispatch_number in('");
        sql.append(ids.replaceAll(",","','"));
        sql.append("') ");
        sql.append(")rs on t1.dispatch_number = rs.dispatch_number ");
        sql.append("set t1.toovolume = rs.tooDeployVolume ");
        sql.append("where t1.dispatch_number = rs.dispatch_number ");
        System.out.println(sql.toString());
        return sql.toString();
    }

    @Override
    public void update(FiOrderAsycParam param){
        FiOrderAsyc oldEntity = getOldEntity(param);
        FiOrderAsyc newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public FiOrderAsycResult findBySpec(FiOrderAsycParam param){
        return null;
    }

    @Override
    public List<FiOrderAsycResult> findListBySpec(FiOrderAsycParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(FiOrderAsycParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(FiOrderAsycParam param){
        return param.getOrderNumber();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private FiOrderAsyc getOldEntity(FiOrderAsycParam param) {
        return this.getById(getKey(param));
    }

    private FiOrderAsyc getEntity(FiOrderAsycParam param) {
        FiOrderAsyc entity = new FiOrderAsyc();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
